package cn.com.checne.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import cn.com.checne.model.domain.BusinessCategory;
import cn.com.checne.model.domain.BusinessInfo;
import cn.com.checne.model.domain.LanguageInfo;
import cn.com.checne.model.dto.BusinessQuery;
import cn.com.checne.util.TimeUtils;


@Repository
public class BusinessInfoDao {
	protected static final Logger log = Logger.getLogger(BusinessInfoDao.class);

	/**
	 * create
	 * @param cate
	 * @return
	 */
	public boolean create(BusinessInfo business) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String createSql = "insert into tbl_business(lg_id_fk,business_cate_id_fk,business_title,business_summary,business_publishdate,business_publishfrom,business_author,business_contenttype,business_content," +
					"business_meta_keyword,business_meta_content,business_isshowindex,business_isshowlist,business_istop,business_firstimage)" +
					" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement pstmt = conn.prepareStatement(createSql);
			int i = 0 ;
			pstmt.setInt(++i,business.getLanguageId());
			pstmt.setInt(++i,business.getCateId());
			pstmt.setString(++i,business.getTitle());
			pstmt.setString(++i,business.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(business.getPublishDate().getTime()));
			pstmt.setString(++i,business.getPublishFrom());
			pstmt.setString(++i,business.getAuthor());
			pstmt.setInt(++i,business.getContentType());
			pstmt.setString(++i,business.getContent());
			
			pstmt.setString(++i,business.getMetaKeyword());
			pstmt.setString(++i,business.getMetaContent());
			
			pstmt.setInt(++i,business.getIsShowIndex());
			pstmt.setInt(++i,business.getIsShowList());
			pstmt.setInt(++i,business.getIsTop());
			
			pstmt.setString(++i,business.getFirstImage());

			pstmt.execute();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param cate
	 * @return
	 */
	public boolean update(BusinessInfo business) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_business set " +
					"lg_id_fk = ?,business_cate_id_fk = ?,business_title = ?,business_summary = ?,business_publishdate =? ,business_publishfrom = ?,business_author =?,business_contenttype=?,business_content=?," +
					"business_meta_keyword =?,business_meta_content=?,business_isshowindex=?,business_isshowlist=?,business_istop=?,business_firstimage=? where business_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,business.getLanguageId());
			pstmt.setInt(++i,business.getCateId());
			pstmt.setString(++i,business.getTitle());
			pstmt.setString(++i,business.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(business.getPublishDate().getTime()));
			pstmt.setString(++i,business.getPublishFrom());
			pstmt.setString(++i,business.getAuthor());
			pstmt.setInt(++i,business.getContentType());
			pstmt.setString(++i,business.getContent());
			
			pstmt.setString(++i,business.getMetaKeyword());
			pstmt.setString(++i,business.getMetaContent());
			
			pstmt.setInt(++i,business.getIsShowIndex());
			pstmt.setInt(++i,business.getIsShowList());
			pstmt.setInt(++i,business.getIsTop());
			
			pstmt.setString(++i,business.getFirstImage());
			
			pstmt.setInt(++i, business.getBusinessId());
			
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param id
	 * @return
	 */
	public boolean delete(int id){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "delete from tbl_business where business_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,id);
			log.info("[SQL]" + pstmt.toString());
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	/**
	 * 
	 * @param BusinessId
	 * @return
	 */
	public BusinessInfo getBusinessById(int businessId) {
		BusinessInfo business = new BusinessInfo();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_business where business_id = ? ";

			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, businessId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<BusinessInfo> list = getResult(rs);
			business = (list != null && list.size() > 0 ) ? list.get(0) : business ;
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return business;
	}
	/**
	 * 
	 * @param query
	 * @param start
	 * @param num
	 * @return
	 */
	public List<BusinessInfo> getBusinessListByCondition(BusinessQuery query,int start,int num) {
		List<BusinessInfo> list = new ArrayList<BusinessInfo>();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_business where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and business_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and business_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and business_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and business_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (business_title like ? or business_meta_keyword like ? or business_meta_content like ? or business_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and business_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and business_publishdate <= ? ";
			}
			sql += "order by business_publishdate desc limit ?,?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			pstmt.setInt(++i, start);
			pstmt.setInt(++i, num);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			list.addAll(getResult(rs));
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 
	 * @param query
	 * @return
	 */
	public int getBusinessCountByCondition(BusinessQuery query) {
		int total = 0 ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select count(1) as total from tbl_business where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and business_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and business_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and business_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and business_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (business_title like ? or business_meta_keyword like ? or business_meta_content like ? or business_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and business_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and business_publishdate <= ? ";
			}
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				total = rs.getInt("total");
			}
			rs.close();
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return total;
	}
	
	
	public boolean setShowIndex(int flag,int...businessIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_business set business_isshowindex = ? where business_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int businessId : businessIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,businessId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public boolean setShowList(int flag,int...businessIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_business set business_isshowlist = ? where business_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int businessId : businessIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,businessId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public BusinessInfo isBusinessExist(int languageId ,int cateId){
		BusinessInfo business = null ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_business where lg_id_fk = ? and business_cate_id_fk = ?   " ;
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			pstmt.setInt(++i, languageId);
			pstmt.setInt(++i, cateId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<BusinessInfo> list = getResult(rs);
			business = (list != null && list.size() > 0 ) ? list.get(0) : null;
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return business ;
	}
	/**
	 * get rseult from resultSet
	 * @param rs
	 * @return
	 */
	public List<BusinessInfo> getResult(ResultSet rs) {
		List<BusinessInfo> list = new ArrayList<BusinessInfo>();
		try {
			BusinessInfo business = null ;
			while(rs.next()) {
				business = new BusinessInfo();
				business.setBusinessId(rs.getInt("business_id"));
				business.setTitle(rs.getString("business_title"));
				business.setSummary(rs.getString("business_summary"));
				business.setPublishDate(rs.getTimestamp("business_publishdate"));
				business.setPublishFrom(rs.getString("business_publishfrom"));
				business.setAuthor(rs.getString("business_author"));
				business.setContentType(rs.getInt("business_contenttype"));
				business.setContent(rs.getString("business_content"));
				business.setMetaKeyword(rs.getString("business_meta_keyword"));
				business.setMetaContent(rs.getString("business_meta_content"));
				business.setIsShowIndex(rs.getInt("business_isshowindex"));
				business.setIsShowList(rs.getInt("business_isshowlist"));
				business.setIsTop(rs.getInt("business_istop"));
				business.setFirstImage(rs.getString("business_firstimage"));
				
				business.setLanguageId(rs.getInt("lg_id_fk"));
				LanguageInfo lg = new LanguageInfoDao().getLanguageInfoById(business.getLanguageId());
				business.setLanguageInfo(lg);
				
				business.setCateId(rs.getInt("business_cate_id_fk"));
				BusinessCategory cate = new BusinessCategoryDao().getBusinessCategory(business.getCateId());
				business.setBusinessCategory(cate);
				
				list.add(business);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
}